﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BeerScanatronUI
{
    /// <summary>
    /// Process scan string to decode scanner and user input Code39 input.
    /// </summary>
    public class ScanCode
    {
        private bool _validCode = false;
        private bool _isCancel = false;
        private bool _isNumericCode = false;
        private int _code = -1;

        /// <summary>
        /// True if scanned code is valid.
        /// </summary>
        public bool IsValid
        {
            get { return _validCode; }
        }

        /// <summary>
        /// True if scanned code is the CANCEL code.
        /// </summary>
        public bool IsCancel
        {
            get { return _isCancel; }
        }

        /// <summary>
        /// 
        /// </summary>
        public bool IsNumericCode
        {
            get { return _isNumericCode; }
        }

        /// <summary>
        /// If Code is -1, scanned code is either invalid or cancel.
        /// Otherwise, Code value will be greater than or equal to zero.
        /// </summary>
        public string Code
        {
            get { return _code.ToString(); }
        }

        public ScanCode(string code)
        {
            if (String.IsNullOrWhiteSpace(code))
            {
                return;
            }

            // Do formating tests if code from scanner.
            int i;
            code = code.Trim();

            // If find embedded space.  Only use chars after it.
            if ((i = code.IndexOf(" ")) > -1)
            {
                code = code.Substring(i + 1);
            }

            // Remove scanner EOD character.
            if (code.EndsWith("a"))
            {
                code = code.Substring(0, code.Length - 1);
            }

            // Try to convert code to number.
            int numericCode = 0;
            if (int.TryParse(code, out numericCode))
            {
                // It's a number.
                _code = numericCode;
                _isNumericCode = true;
                _validCode = true;
            }
            else
            {
                // Must have alpha chars.  Is is CANCEL?
                if (code == "CANCEL")
                {
                    _isCancel = true;
                    _validCode = true;
                }
            }
        }
    }
}
